<?php

namespace App\Admin\Controllers;

use Encore\Admin\Layout\Content;
use Carbon\Carbon;
use App\Models\Collection;
use App\Models\SeckillProduct;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Actions\CollectionAction\CollectionImages;
use App\Admin\Actions\CollectionAction\Materials;
use App\Admin\Actions\CollectionAction\BatchImgCreate;
use App\Admin\Tools\BatchCreateCombination;
use ZipArchive;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;


class CollectionsController extends AdminController
{
    protected $title = '合成图合集';
    
    protected function grid()
    {
        $grid = new Grid(new Collection());
	
	    $grid->disableExport();
	    
	    $grid->column('id', 'ID');
        $grid->column('title', '标题');
        $this->gridActions($grid);
         $this->gridTools($grid);
      
        return $grid;
    }
    
     protected function gridTools(Grid $grid)
    {
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new BatchCreateCombination());
        });
    }

    protected function gridActions(Grid $grid)
    {
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableView();
            $actions->add(new CollectionImages());
            $actions->add(new Materials());
            $actions->add(new BatchImgCreate());
        });
    }


    protected function detail($id)
    {
        $show = new Show(Collection::findOrFail($id));

        return $show;
    }

    
    protected function form()
    {
        $form = new Form(new Collection());
        $form->text('title', '标题');
       // $this->formSaved($form);

        return $form;
    }


    public function combinationForm()
    {
        if ($collection = Collection::query()->doesntExist()) {
            admin_toastr('无数据合集', 'error');
            return redirect()->back();
        }

        $collection = Collection::query()->get();
        $images = [];
        foreach($collection as $k=>$v){

            $images[$k] = $v->collectionImages->toArray();
        }

        $minLength = count(min($images));
        $imageLegth = count($images);
         $arr = [];
        for($i=0;$i<$minLength;$i++){
          //  if($i==0){
                foreach($images as $k=>$v){

                    $arr[$i][] = $v[$i]['image'];
                }

         //   }
           


        }

        $zip = new ZipArchive();
        $zipFileName = 'export-'.date("YmdHis",time()).'.zip';

        if ($zip->open($zipFileName, ZipArchive::CREATE) === TRUE) {
            // 添加文件夹到ZIP中
             foreach($arr as $k=>$res){
                $localPath = $this->getLocalPosterSavePath();
                foreach($res as $rr){
                    //dd(file_get_contents($rr));
                    $dds = explode("/",$rr);
                    $baseName = array_pop($dds);

                    $aa = $zip->addFile($localPath.'/'.$baseName,"group{$k}/".$baseName);
                }
               // dd($localPath);
                
                 //$zip->addEmptyDir($localPath);
                 //File::deleteDirectory($localPath);
            }
           // chmod(public_path($zipFileName), 0644);
            $zip->close();
         
            // 下载ZIP文件

            $name = basename(public_path($zipFileName)); 

            Storage::putFileAs('orders/export', public_path($zipFileName), $name);
            File::deleteDirectory(public_path($zipFileName));
            //response()->download(public_path($zipFileName),$name ,$headers = ['Content-Type'=>'application/zip;charset=utf-8']);
        } else {
            // 错误处理
            response()->json(['error' => 'Cannot create ZIP file'], 500);
        }
       

       
        return redirect()->back();

       /* dd(123);
        $time = Carbon::now()->toDateTimeString();

        (new OrderExport())->queue("orders/export/{$time}-导出普通待发货订单.xlsx", 'alioss');
        admin_toastr('导出普通待发货订单已提交', 'success');*/
        //return redirect('/admin/orders/undelivered/exports');
    }

   /* public function makeImage($filePath,$image){
        $imgModel = Image::canvas(750, 1000, '#FFFFFF');

       
        $image =  Image::make(img_path($image))->resize(750, 1000);

        $imgModel->insert($image, 'top', 0, 0);
        
        $baseName = $this->getPosterName().".png";
        $imgModel->save($filePath."/".$baseName);

        return $baseName;
    }*/

    protected function getPosterName()
    {
        return (string)serial_uuid();
    }
    
    
    protected function getLocalPosterSavePath()
    {
        $localPath = public_path('temp/ai-create-image');
        if (! File::isDirectory($localPath)) {
             //chmod($localPath, 755);
             admin_toastr('原始数据已删除，请重新生成原始合成图数据', 'error');
            //File::makeDirectory($localPath, 755, true, true);
        }
        return $localPath;
    }
  
}
